package com.wyk.redis;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.collections.SetUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.StringUtils;

import com.google.common.primitives.Bytes;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class RedisManager{
	
	private JedisPool jedisPool;
	
	private final Integer INDEX = 1;
	
	public JedisPool getJedisPool() {
		return jedisPool;
	}
	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}

	public void set(String key,byte[]value){
		if(StringUtils.isBlank(key) || ArrayUtils.isEmpty(value))
			return;
		try(Jedis jedis = jedisPool.getResource()){
			jedis.select(INDEX);
			jedis.set(key.getBytes(), value);
		}
	}
	
	public <T> T get(String key){
		if(StringUtils.isBlank(key))
			return null;
		try(Jedis jedis = jedisPool.getResource()){
			jedis.select(INDEX);
			byte[] bs = jedis.get(key.getBytes());
			if(ArrayUtils.isEmpty(bs)){
				return null;
			}
			return SerializationUtils.deserialize(bs);
		}
	}
	
	public void delete(String key){
		if(StringUtils.isBlank(key))
			return;
		try(Jedis jedis = jedisPool.getResource();){
			jedis.select(INDEX);
			jedis.del(key.getBytes());
		}
	}
	
	@SuppressWarnings("unchecked")
	public Set<String> keys(String pattern){
		if(StringUtils.isBlank(pattern))
			return SetUtils.EMPTY_SET;
		try(Jedis jedis = jedisPool.getResource()){
			jedis.select(INDEX);
			return jedis.keys(pattern);
		}
	}
	
	public void expires(String key,long time,TimeUnit timeUnit){
		try(Jedis jedis = jedisPool.getResource()){
			jedis.select(INDEX);
			long seconds = timeUnit.toSeconds(time);
			jedis.expire(key,(int)seconds);
		}
	}
}